package com.lvyq.myplayer.base

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.SharedPreferences
import android.os.Bundle
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import coil.load
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.util.ImgAnimatorUtils
import com.lvyq.myplayer.common.util.PaletteColorUtils
import com.lvyq.myplayer.common.util.StartActivityUtils
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.common.EventPlayerViewModel
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.service.IService
import com.lvyq.myplayer.ui.fragment.music.MainMusicPagerFragment
import com.lvyq.myplayer.widget.audio.AudioListPopWindow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.find


/**
 * activity基类
 */
abstract class BaseActivity :AppCompatActivity(){

    val playCurrentPlayLstDao by lazy { PlayerDatabase.getDatabase(this).currentPlayLstDao() }

    open var currentPlayAdapter: CurrentPlayLstAdapter?=null

    private lateinit var playerMainStateViewModel: EventPlayerViewModel


     lateinit var cardView :CardView
     lateinit var mainMusicBg:ShapeableImageView
     lateinit var mainMusicLayOut: LinearLayout
     lateinit var musicBoxPlay :ImageView
     lateinit var musicBoxNext:ImageView
     lateinit var musicBoxList:ImageView
     lateinit var mainMusicPlayPager:ViewPager2
     var animatorUtils: ImgAnimatorUtils? = null
    lateinit var tab: TabLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        initData()
        initListener()

    }

    /**
     * 初始化数据
     */
    open protected fun initData() {
    }

    /**
     * adpter listener
     */
   open protected fun initListener() {
    }

    /**
     * 获取布局id
     */
    abstract fun getLayoutId(): Int

    fun myToast(msg:String){
        runOnUiThread {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 进入界面
     */
    inline fun < reified T> startActivityAndFinish(){
        //进入界面
        var intent = Intent(this, T::class.java)
        startActivity(intent)
        finish()
    }



// IService 相关
    companion object{
        private var TAG ="BaseActivity"
        val connection by lazy { AudioConnection() }
        var iService: IService?= null
        class AudioConnection: ServiceConnection {
            /**
             * service 连接时
             */
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                iService=service as IService

                Log.i(TAG,"AudioServiceManager>连接成功")
            }

            //意外味断开连接
            override fun onServiceDisconnected(name: ComponentName?) {
                Log.i(TAG,"AudioServiceManager>意外断开")
                iService=null
            }

        }

    }



    // 唱针旋转动画
    fun startNeedleAnimation(needle: ImageView) {
        needle.pivotX = needle.width.toFloat()/2    // 以左侧为旋转支点
        needle.pivotY = 0f   // 以顶部为旋转支点
        // 设置初始旋转角度（20度倾斜）
        needle.rotation = -20f
        //确保唱针位于最上层
        needle.bringToFront()

    }

    /**
     * 唱针回位
     */
    fun resetNeedleAnimation(needle: ImageView) {

        needle.pivotX = needle.width.toFloat()/2    // 以左侧为旋转支点
        needle.pivotY = 0f   // 以顶部为旋转支点
        // 设置初始旋转角度（20度倾斜）
        needle.rotation = 0f
        //确保唱针位于最上层
        needle.bringToFront()

    }

    fun  initMainPlayBoxListener(){
        var songInfo = MainAudioSharedPrefsManager.getSongInfo(this)

        mainMusicBg=find(R.id.main_music_bg)
        mainMusicLayOut=find(R.id.main_music_layout)

        musicBoxPlay = findViewById(R.id.music_box_play)
        musicBoxNext=findViewById(R.id.music_box_next)
        cardView=findViewById(R.id.music_card)
        mainMusicPlayPager=findViewById(R.id.playAudioLst)
        tab=findViewById(R.id.tab)



        songInfo?.let {
            // 确保视图加载完成
            mainMusicBg.load(it.bgImg){
                placeholder(R.mipmap.yinle_1) // 加载中占位图
                error(R.mipmap.yinle_1)       // 加载失败显示
                crossfade(true)    // 淡入动画
            }
            //改变背景色
            lifecycleScope.launch {
                PaletteColorUtils.setBoxBackColor(this@BaseActivity,it.bgImg,cardView)
            }
        }

        musicBoxList=findViewById<ImageView>(R.id.music_box_list)

        musicBoxList.setOnClickListener {
            var  bottom=findViewById<LinearLayout>(R.id.music_box)
            var songInfoList = MainAudioSharedPrefsManager.getSongInfoList(this)
            songInfoList?.let { it -> currentPlayAdapter?.initData(it) }
            var playLstWindow = AudioListPopWindow(this,currentPlayAdapter,iService)
            if (!playLstWindow.isShowing){
                //Gravity.BOTTOM强制从底部开始计算位置   bottom.height  向下偏移容器高度 ,使底部位于播放栏的上方
                playLstWindow.showAsDropDown(bottom, Gravity.BOTTOM,0, bottom.height)
            }
        }

        musicBoxPlay.setOnClickListener {
            updateMainPlayStateBtn(false)
        }

        musicBoxNext.setOnClickListener {
            iService?.nextMusicPlay()
        }


    }




    /**
     * 初始化播放列表 -通用
     */
    fun initAudioPlayLst(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            playCurrentPlayLstDao.getAllCurrentPlayLstFlow()
                //.conflate()
                .collect { list ->
                    val playList = list.map { song ->
                        SongInfoData(
                            song.businessKey,
                            song.bgImg,
                            song.title,
                            song.lrc,
                            song.url,
                            song.singer,
                            song.singerId,
                            song.publishDate,
                            song.albumId,
                            song.albumName,
                            null,
                            song.reNum,
                            null,
                            null,
                            null,
                            song.position,
                            null
                        )
                    }.toCollection(arrayListOf())

                    MainAudioSharedPrefsManager.saveSongInfoList(context,playList)
                    // 切换到主线程更新UI
                    //TODO 在删除播放列表中的单曲时会频繁多次调用，也许后期会单纯采用Shared的方式调用initAudioPlayLst，
                    withContext(Dispatchers.Main) {
                        currentPlayAdapter?.initData(playList)
                        //更新播放列表
                        iService?.initAudioPlayLst(playList)

                    }
                }
        }
    }


    /**
     * 播放监听，播放状态UI、播放中图标
     */
    fun initMainPlayStateChangeUI() {
        animatorUtils=ImgAnimatorUtils(mainMusicBg)
        // 启动动画（60秒周期）
        animatorUtils?.startInfiniteRotation()

        // 初始化 ViewModel
        playerMainStateViewModel = ViewModelProvider(this)[EventPlayerViewModel::class.java]
        // 观察状态变化
        playerMainStateViewModel.eventPlayState.observe(this) { eventState ->
            // 在这里处理状态变化
            if (eventState.playState){
                //播放中 ，将按钮更为暂停
                musicBoxPlay.setImageResource(R.mipmap.music_box_stop)
                animatorUtils?.toggleRotation(true)
            }else{
                musicBoxPlay.setImageResource(R.mipmap.music_box_start)
                animatorUtils?.toggleRotation(false)
            }
        }
        //播放图标更新
        playerMainStateViewModel.eventCurSongId.observe(this){eventCurrentSongId->
            currentPlayAdapter?.let {
                it.refreshPlayPosition(eventCurrentSongId.ponsiton)
            }
        }
        //切换歌曲 .虽然不如EventBus逻辑直观。但好在可以很好的监听歌曲切换
        playerMainStateViewModel.eventPlaySong.observe(this){data->
            mainMusicBg.load(data.bgImg)
           /* mainMusicTitle.text=data.title
            mainMusicSinger.text=data.singer*/
            //改变背景色
            lifecycleScope.launch {
               PaletteColorUtils.setBoxBackColor(this@BaseActivity,data.bgImg,cardView)
            }
            //更新页面
            val currentPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this)?.toInt()?:0
            mainMusicPlayPager.setCurrentItem(currentPosition, false)

        }

    }

     fun updateMainPlayStateBtn( isPlayStart:Boolean) {
        var playState = iService?.updPlayState(isPlayStart)
        playState?.let {
            //更新ui
            if (playState) {
                //播放中 ，将按钮更为暂停
                musicBoxPlay.setImageResource(R.mipmap.music_box_stop)
            } else {
                //暂停，将按钮更为播放中
                musicBoxPlay.setImageResource(R.mipmap.music_box_start)
            }
        }
    }

    /**
     * 更新fragment
     */
    fun recreateViewPagerAdapter() {
        val audioLst = MainAudioSharedPrefsManager.getSongInfoList(this)

        // 保存当前播放位置
        val currentPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this)?.toInt()?:0

        // 创建新适配器
        mainMusicPlayPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = audioLst.size

            override fun createFragment(position: Int): Fragment {
                return MainMusicPagerFragment(audioLst[position]).apply {
                    setOnItemClickListener(object : MainMusicPagerFragment.OnMainMusicClickListener {
                        override fun onMainMusicClick(position: Int, songInfoData: SongInfoData) {
                            var songInfoList = MainAudioSharedPrefsManager.getSongInfoList(this@BaseActivity)
                            var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this@BaseActivity)
                            StartActivityUtils.startAudioPlayerActivityAndSaveDB(this@BaseActivity, songInfoList,currentAudioPosition?.toInt()?:0)
                        }
                    })
                }
            }
        }

        // 重新关联TabLayout
        TabLayoutMediator(tab, mainMusicPlayPager) { tab, position ->
            tab.text = position.toString()
        }.attach()

        //默认页面
        mainMusicPlayPager.setCurrentItem(currentPosition, false)



        //滑动事件
        mainMusicPlayPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                // 页面滑动中（实时回调）
            }

            override fun onPageSelected(position: Int) {
                // 新页面被选中时触发
                Log.d("ViewPager2", "当前页: $position")
                BaseActivity.iService?.musicPlayPosition(position,audioLst.get(position))
            }

            override fun onPageScrollStateChanged(state: Int) {
                when (state) {
                    ViewPager2.SCROLL_STATE_IDLE -> Log.d("ViewPager2", "滑动停止")
                    ViewPager2.SCROLL_STATE_DRAGGING -> Log.d("ViewPager2", "用户拖拽中")
                    ViewPager2.SCROLL_STATE_SETTLING -> Log.d("ViewPager2", "自动滑动中")
                }
            }
        })
    }



}


